﻿namespace ThreeByte.ActiveDeck.Dashboard
{
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using ThreeByte.ActiveDeck.Web;
using System.ServiceModel.DomainServices.Client;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
    using System.Windows.Media;

    /// <summary>
    /// Home page for the application.
    /// </summary>
    public partial class Account : Page
    {
        /// <summary>
        /// Creates a new <see cref="Home"/> instance.
        /// </summary>
        public Account() {
            InitializeComponent();

        }

        private Web.User _thisUser;
        /// <summary>
        /// Executes when the user navigates to this page.
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e) {
            WebContext.Current.Authentication.LoadUser();
            
            _thisUser = WebContext.Current.User;
            LayoutRoot.DataContext = WebContext.Current.User;

            string roleString = string.Empty;
            foreach(string role in _thisUser.Roles) {
                if(string.IsNullOrEmpty(roleString)) {
                    roleString = role;
                } else {
                    roleString += @", " + role;
                }
            }
            AccountTypeText.Text = roleString;
            SetMessage();
            UpdateSaveButton();

            _dashboardContext.IsEmailVerified(EmailVerified_Complete, null);
        }

        private DashboardAccessContext _dashboardContext = new DashboardAccessContext();

        private void EmailVerified_Complete(InvokeOperation<bool> op) {
            if(!(op.HasError) && op.Value) {
                EmailVerifiedText.Visibility = System.Windows.Visibility.Visible;
                return;
            }

            VerifyEmailHyperlink.Visibility = System.Windows.Visibility.Visible;
        }


        private void SaveChangesButton_Click(object sender, System.Windows.RoutedEventArgs e) {
            //Validate the fields that have changed
            if(!IsFormValid()) {
                return;
            }

            SaveIndicator.IsBusy = true;
            //Submit profile updates first
            WebContext.Current.Authentication.SaveUser(SaveUserCompleted, null);
            
        }

        private void SaveUserCompleted(SaveUserOperation op) {
            if(!(op.HasError)) {
                //Mark as success
                SetMessage("Your profile has been updated");
            } else {
                //Mark as Error
                SetMessage("Your profile could not be updated", true);
            }

            if(!(ChangePasswordCheckBox.IsChecked ?? false)) {
                //Change the password
                SaveIndicator.IsBusy = false;
                WebContext.Current.Authentication.LoadUser();
                return;
            }

            //Then submit password change if necessary
            _userContext = new UserRegistrationContext();
            _userContext.ChangeUserPassword(CurrentPasswordBox.Password, NewPasswordBox.Password, ChangePasswordCompleted, null);
            CurrentPasswordBox.Password = string.Empty;
            NewPasswordBox.Password = string.Empty;
            ConfirmPasswordBox.Password = string.Empty;
        }

        private UserRegistrationContext _userContext;

        private void ChangePasswordCompleted(InvokeOperation<bool> op) {
            if(!(op.HasError) && op.Value) {
                SetMessage("Your password was changed succesfully");
                ChangePasswordCheckBox.IsChecked = false;
            } else {
                SetMessage("Password could not be changed", true);
            }
            SaveIndicator.IsBusy = false;
            WebContext.Current.Authentication.LoadUser();
        }

        private bool IsFormValid() {

            if(ChangePasswordCheckBox.IsChecked ?? false) {
                if(string.IsNullOrWhiteSpace(CurrentPasswordBox.Password)) {
                    SetMessage("Please enter your current password", true);
                    CurrentPasswordBox.Focus();
                    return false;
                }
                if(string.IsNullOrWhiteSpace(NewPasswordBox.Password)) {
                    SetMessage("Please enter a new password", true);
                    NewPasswordBox.Focus();
                    return false;
                }
                if(NewPasswordBox.Password != ConfirmPasswordBox.Password) {
                    SetMessage("Passwords do not match", true);
                    NewPasswordBox.Focus();
                    NewPasswordBox.SelectAll();
                    return false;
                }
            }

            return true;
        }


        private void SetMessage(string message = null, bool error = false) {
            if(error) {
                MessageText.Text = null;
                ErrorText.Text = message;
            } else {
                MessageText.Text = message;
                ErrorText.Text = null;
            }
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e) {
            UpdateSaveButton();
        }

        private void PasswordBox_PasswordChanged(object sender, System.Windows.RoutedEventArgs e) {
            UpdateSaveButton();
        }

        private void UpdateSaveButton() {
            SaveButton.IsEnabled = (_thisUser.HasChanges || (ChangePasswordCheckBox.IsChecked ?? false));
        }

        private void VerifyEmailButton_Click(object sender, System.Windows.RoutedEventArgs e) {
            //Send an email now
            _dashboardContext.SendEmailVerification(SendEmailComplete, null);
            VerifyEmailHyperlink.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void SendEmailComplete(InvokeOperation op) {
            if(op.HasError) {
                SetMessage("Error: Email could not be sent", true);
                op.MarkErrorAsHandled();
            } else {
                SetMessage("Please check your email, and click the included link to complete the verification process");
            }

        }
    }
}